package service

import (
	"context"
	"disk/disk_rpc_server/disk_pb"
	"disk/utils/mysql"
	"gorm.io/gorm"
)

func (*GrpcServer) Query(ctx context.Context, req *disk_pb.QueryReq) (resp *disk_pb.QueryResp, err error) {
	db := Database.Session(&gorm.Session{NewDB: true})
	var dataList []mysql.DiskList
	var resultList []*disk_pb.DiskList
	name := req.GetName()

	result := db.Where("name = ?", name).Find(&dataList)
	mysql.DiskListOrmToRpc(dataList, &resultList)
	if result.Error != nil {
		return &disk_pb.QueryResp{
			Code:    1,
			Message: "查询失败" + result.Error.Error(),
			List:    resultList,
		}, nil
	}

	return &disk_pb.QueryResp{
		Code:    0,
		Message: "查询成功",
		List:    resultList,
	}, nil
}

func (*GrpcServer) QueryPage(ctx context.Context, req *disk_pb.QueryPageReq) (resp *disk_pb.QueryPageResp, err error) {
	db := Database.Session(&gorm.Session{NewDB: true})
	var dataList []mysql.DiskList
	var resultList []*disk_pb.DiskList
	pageSize := int(req.GetPageSize())
	pageNum := int(req.GetPageNum())

	db = db.Model(dataList)
	allQueries := req.QueryParams
	for key, val := range allQueries {
		db.Where(key+" LIKE ?", "%"+val+"%")
	}

	//limit(-1)表示查询全部数据，offset表示跳过多少条
	var total int64
	db.Count(&total).Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&dataList)

	mysql.DiskListOrmToRpc(dataList, &resultList)
	if len(resultList) == 0 {
		return &disk_pb.QueryPageResp{
			Code:    1,
			Total:   0,
			Message: "没有查到",
			List:    resultList,
		}, nil
	} else {
		return &disk_pb.QueryPageResp{
			Code:    0,
			Total:   total,
			Message: "查询成功",
			List:    resultList,
		}, nil
	}
}
